package com.xoa.controller.workflow;

import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.response.OapiCalendarListResponse;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dao.workflow.FlowAssignMapper;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.fixAssets.EduFixAssets;
import com.xoa.model.users.Users;
import com.xoa.model.workflow.FlowAssign;
import com.xoa.model.workflow.FlowAssignWithBLOBs;
import com.xoa.model.workflow.FlowProcess;
import com.xoa.model.workflow.FlowRunPrcs;
import com.xoa.service.WFE.WFEFactory.WFEFlowProcess;
import com.xoa.service.WFE.WFERunner.WFERunner;
import com.xoa.service.sms.SmsService;
import com.xoa.service.users.UsersService;
import com.xoa.service.workflow.FlowAssign.FlowAssignService;
import com.xoa.util.CookiesUtil;
import com.xoa.util.ToJson;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import org.omg.PortableServer.ID_ASSIGNMENT_POLICY_ID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@Scope(value = "prototype")
@RequestMapping("/flowAssign")
public class FlowAssignController {
    @Autowired
    protected WFERunner wfeRunner;
    @Autowired
    protected FlowAssignService flowAssignService;
    @Autowired
    protected UsersMapper usersMapper;
    @Autowired
    protected WFEFlowProcess wfeFlowProcess;
    @Autowired
    protected SmsService smsService;
    @Autowired
    protected FlowAssignMapper flowAssignMapper;


    @RequestMapping(value = "workUpload", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    @ResponseBody
    public void workUpload(@RequestParam(value = "file", required = false) MultipartFile[] files, String module,
                           HttpServletRequest request, HttpServletResponse response) throws IOException {
        String company = ContextHolder.getConsumerType();
        String flowPrcs = request.getParameter("flowPrcs");
        if (StringUtils.checkNull(company) || company.contains("null")) {
            company = "xoa1001";
        }
        ToJson<Attachment> toJson = wfeRunner.getWfeFlowRunInfo().workUpload2(files, company, module, request);
        response.setHeader("content-type", "text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        ServletOutputStream out = response.getOutputStream();
        OutputStreamWriter ow = new OutputStreamWriter(out, "UTF-8");

        ow.write(JSONObject.toJSONString(toJson));
        ow.flush();
        ow.close();
    }

    @RequestMapping("/flowAssignDetail")
    public String flowAssignDetail() {
        return "/app/workflow/work/flowAssignDetail";
    }

    @ResponseBody
    @RequestMapping("/selectFeedBack")
    public ToJson<FlowProcess> selectFeedBack(Integer flowId, Integer prcsId) {
        return flowAssignService.selectFeedBack(flowId, prcsId);
    }

    @RequestMapping("/saveWork")
    @ResponseBody
    public ToJson<FlowRunPrcs> savework(HttpServletRequest request,
                                        @RequestParam(value = "runId", required = false) Integer runId,
                                        @RequestParam(value = "runName", required = false) String runName,
                                        @RequestParam(value = "flowId", required = false) Integer flowId,
                                        @RequestParam(value = "prcsId", required = false) Integer prcsId,
                                        @RequestParam(value = "prcsflag", required = false) String prcsFlag,
                                        @RequestParam(value = "flowPrcs", required = false) String flowPrcs,
                                        @RequestParam(value = "beginTime", required = false) String beginTime,
                                        @RequestParam(value = "beginUser", required = false) String beginUser,
                                        @RequestParam(value = "jingbanUser", required = false) String jingbanUser,
                                        @RequestParam(value = "currentPrcsId", required = false) Integer currentPrcsId,
                                        @RequestParam(value = "orgAdd", required = false) String orgadd,
                                        @RequestParam(value = "viewUser", required = false) String viewUser,
                                        @RequestParam(value = "smsContent", required = false) String smsContent,
                                        @RequestParam(value = "smsType", required = false) String smsType,
                                        @RequestParam(value = "tableName", required = false) String tableName,
                                        @RequestParam(value = "tabId", required = false) String tabId,
                                        @RequestParam(value = "flowStep", required = false) String flowStep,
                                        @RequestParam(value = "prcsName", required = false) String prcsName,
                                        @RequestParam(value = "assignTask", required = false) String assignTask,
                                        @RequestParam(value = "signYn", required = false) String signYn,
                                        @RequestParam(value = "attachmentId", required = false) String attachmentId,
                                        @RequestParam(value = "attachmentName", required = false) String attachmentName,
                                        String parent, String topFlag

    ) {
        /*smsType="5,6";*/
        String tuisong = request.getParameter("tuisong");
        String topDefault = "0";
        String userId = request.getParameter("userId");
        Users user = null;

        //解决工作监控代为转交
        if (StringUtils.checkNull(userId)) {
            // Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            //user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        } else {
            user = usersMapper.findUsersByuserId(userId);
        }


        //经办人数组
        String[] alljingbanArray = jingbanUser.split("\\|");
        String[] jingbanArray = null;
        String branchCount = null;
        //用来判断发送事务提醒
        /*currentPrcsId=1;*/
        FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(flowId, currentPrcsId);

        //主办人提交消除事物提醒（结束流程时没有主办人）
        //String[] strs1 = flowPrcs.split(",");
        String smsUrl = null;
        if ("2".equals(flowProcess.getTopDefault())) {
            smsUrl = "/workflow/work/workform?opflag=0&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + currentPrcsId;
        } else {
            smsUrl = "/workflow/work/workform?opflag=1&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + currentPrcsId;
        }
        if ("document".equals(tableName)) {
            smsUrl = "/workflow/work/workform?opflag=1&flowId=" + flowId + "&flowStep=" + flowStep + "&tableName=" + tableName + "&tabId=" + tabId + "&runId=" + runId + "&prcsId=" + currentPrcsId + "&isNomalType=false";
            smsService.updatequerySmsByType("70", user.getUserId(), smsUrl.trim());
        } else if ("budget".equals(tableName)) {
            smsUrl += "&tableName=budget";
            smsService.updatequerySmsByType("7", user.getUserId(), smsUrl.trim());
        } else {
            smsService.updatequerySmsByType("7", user.getUserId(), smsUrl.trim());
        }
        Date date = new Date();

        FlowAssignWithBLOBs f = new FlowAssignWithBLOBs();
        f.setRunId(runId);
        f.setPrcsId(prcsId);
        f.setAssignUser(user.getUserId());
        List<FlowAssignWithBLOBs> flowAssignWithBLOBs = flowAssignMapper.selectFlowAssign(f);
        String[] split = jingbanUser.split(",");
        String[] split1 = flowAssignMapper.selectTimeOut(flowId, currentPrcsId).split(",");
        for (String s : split) {
            FlowAssignWithBLOBs flowAssign = new FlowAssignWithBLOBs();
            flowAssign.setRunId(runId);
            flowAssign.setPrcsId(prcsId);
            flowAssign.setPrcsName(prcsName);
            flowAssign.setFlowPrcs(Integer.parseInt(flowPrcs));
            flowAssign.setAssignUser(user.getUserId());
            flowAssign.setAssignUser(user.getUserId());
            flowAssign.setAssignTime(new Date());
            flowAssign.setAssignTask(assignTask);
            flowAssign.setSingYn(signYn);
            flowAssign.setAttachmentId(attachmentId);
            flowAssign.setAttachmentName(attachmentName);
            flowAssign.setHandleUser(s);
            flowAssign.setHandleHour(split1[0]);
            flowAssign.setHandleStatus(1);
            flowAssignService.insertAssign(flowAssign);
        }

        StringBuffer stringBuffer1 = new StringBuffer();

        if (flowAssignWithBLOBs != null && !flowAssignWithBLOBs.isEmpty()) {
            String[] split3 = jingbanUser.split(",");
            int i = 0;
            int o = 0;
            for (String s : split3) {
                for (FlowAssignWithBLOBs flowAssignWithBLOBs1 : flowAssignWithBLOBs) {
                    String handleUser = flowAssignWithBLOBs1.getHandleUser();
                    if (!s.equals(flowAssignWithBLOBs1.getHandleUser())) {
                        i++;
                    }

                }
                if (i == flowAssignWithBLOBs.size()) {
                    if (o == 0) {
                        stringBuffer1.append(s);
                    }
                    if (o > 0) {
                        stringBuffer1.append("," + s);
                    }
                    o++;
                    i = 0;
                }
            }

            jingbanUser = stringBuffer1.toString();
        }

        /*flowPrcs="2";*/

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        beginTime = sdf.format(date);
        String[] split2 = jingbanUser.split(",");
        StringBuffer stringBuffer = new StringBuffer();
        int x = 0;
        for (String s1 : split2) {
            if (!s1.equals(user.getUserId())) {
                if (x == 0) {
                    stringBuffer.append(s1);

                }
                if (x > 0) {
                    stringBuffer.append("," + s1);
                }
                x++;
            }
        }
        jingbanUser = stringBuffer.toString();
        if (StringUtils.checkNull(jingbanUser)) {
            return null;
        }
        return wfeRunner.getWfeFlowRunInfo().savework2(runId, runName, prcsId, flowPrcs, beginTime, beginUser, jingbanUser, viewUser, user, currentPrcsId, topDefault, tabId, tableName, smsContent, smsType, orgadd,parent,topFlag);

        //return wfeRunner.getWfeFlowRunInfo().savework(runId, runName, flowId, prcsId, prcsFlag, flowStep, flowPrcs, beginTime, beginUser, jingbanUser, viewUser, user, currentPrcsId, topDefault, tabId, branchCount);

    }


    @RequestMapping("/update")
    @ResponseBody
    public ToJson<FlowAssignWithBLOBs> updateFlowAssign(String assignId,
                                                        String fdAttachmentID,
                                                        String fdAttachmentName,
                                                        String taskFeedback,
                                                        Integer id,
                                                        String smsType,
                                                        String smsContent,
                                                        HttpServletRequest request,
                                                        Integer runId,
                                                        Integer flowId,
                                                        Integer prcsId,
                                                        Integer currentPrcsId,
                                                        String runName,
                                                        String tableName,
                                                        String tabId
                                                        ) {
        return flowAssignService.updateFlowAssign(assignId,fdAttachmentID,fdAttachmentName, taskFeedback, id, smsType, smsContent, request, runId, flowId, prcsId, currentPrcsId,
                 runName, tableName, tabId);
    }

    @RequestMapping("/saveWork2")
    @ResponseBody
    public ToJson<FlowRunPrcs> savework2(HttpServletRequest request,
                                         @RequestParam(value = "runId", required = false) Integer runId,
                                         @RequestParam(value = "runName", required = false) String runName,
                                         @RequestParam(value = "flowId", required = false) Integer flowId,
                                         @RequestParam(value = "prcsId", required = false) Integer prcsId,
                                         @RequestParam(value = "prcsflag", required = false) String prcsFlag,
                                         @RequestParam(value = "flowPrcs", required = false) String flowPrcs,
                                         @RequestParam(value = "beginTime", required = false) String beginTime,
                                         @RequestParam(value = "beginUser", required = false) String beginUser,
                                         @RequestParam(value = "jingbanUser", required = false) String jingbanUser,
                                         @RequestParam(value = "currentPrcsId", required = false) Integer currentPrcsId,
                                         @RequestParam(value = "orgAdd", required = false) String orgadd,
                                         @RequestParam(value = "viewUser", required = false) String viewUser,
                                         @RequestParam(value = "smsContent", required = false) String smsContent,
                                         @RequestParam(value = "smsType", required = false) String smsType,
                                         @RequestParam(value = "tableName", required = false) String tableName,
                                         @RequestParam(value = "tabId", required = false) String tabId,
                                         @RequestParam(value = "flowStep", required = false) String flowStep,
                                         @RequestParam(value = "prcsName", required = false) String prcsName,
                                         @RequestParam(value = "assignTask", required = false) String assignTask,
                                         @RequestParam(value = "signYn", required = false) String signYn,
                                         @RequestParam(value = "attachmentId", required = false) String attachmentId,
                                         @RequestParam(value = "attachmentName", required = false) String attachmentName,
                                         @RequestParam(value = "assignId", required = false) Integer assignId,
                                         String parent, String topFlag
    ) {
        String tuisong = request.getParameter("tuisong");
        String topDefault = "0";
        String userId = request.getParameter("userId");
        Users user = null;

        //解决工作监控代为转交
        if (StringUtils.checkNull(userId)) {
            // Cookie redisSessionCookie = CookiesUtil.getCookieByName(request, "redisSessionId");
            //user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionCookie);
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(), redisSessionId);
        } else {
            user = usersMapper.findUsersByuserId(userId);
        }


        //经办人数组
        String[] alljingbanArray = jingbanUser.split("\\|");
        String[] jingbanArray = null;
        String branchCount = null;
        //用来判断发送事务提醒
        /*currentPrcsId=1;*/
        FlowProcess flowProcess = wfeFlowProcess.findbyprcsId(flowId, currentPrcsId);

        //主办人提交消除事物提醒（结束流程时没有主办人）
        //String[] strs1 = flowPrcs.split(",");
        String smsUrl = null;
        if ("2".equals(flowProcess.getTopDefault())) {
            smsUrl = "/workflow/work/workform?opflag=0&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + currentPrcsId;
        } else {
            smsUrl = "/workflow/work/workform?opflag=1&flowId=" + Integer.valueOf(flowId) + "&flowStep=" + flowStep + "&runId=" + runId + "&prcsId=" + currentPrcsId;
        }
        if ("document".equals(tableName)) {
            smsUrl = "/workflow/work/workform?opflag=1&flowId=" + flowId + "&flowStep=" + flowStep + "&tableName=" + tableName + "&tabId=" + tabId + "&runId=" + runId + "&prcsId=" + currentPrcsId + "&isNomalType=false";
            smsService.updatequerySmsByType("70", user.getUserId(), smsUrl.trim());
        } else if ("budget".equals(tableName)) {
            smsUrl += "&tableName=budget";
            smsService.updatequerySmsByType("7", user.getUserId(), smsUrl.trim());
        } else {
            smsService.updatequerySmsByType("7", user.getUserId(), smsUrl.trim());
        }
        Date date = new Date();

        FlowAssignWithBLOBs f = new FlowAssignWithBLOBs();
        f.setRunId(runId);
        f.setPrcsId(prcsId);
        f.setAssignUser(user.getUserId());
        List<FlowAssignWithBLOBs> flowAssignWithBLOBs = flowAssignMapper.selectFlowAssign(f);
        String[] split = jingbanUser.split(",");
        String[] split1 = flowAssignMapper.selectTimeOut(flowId, prcsId).split(",");
        for (String s : split) {
            FlowAssignWithBLOBs flowAssign = new FlowAssignWithBLOBs();
            flowAssign.setRunId(runId);
            flowAssign.setPrcsId(prcsId);
            flowAssign.setPrcsName(prcsName);
            flowAssign.setFlowPrcs(Integer.parseInt(flowPrcs));
            flowAssign.setAssignUser(user.getUserId());
            flowAssign.setAssignUser(user.getUserId());
            flowAssign.setAssignTime(new Date());
            flowAssign.setAssignTask(assignTask);
            flowAssign.setSingYn(signYn);
            flowAssign.setAttachmentId(attachmentId);
            flowAssign.setAttachmentName(attachmentName);
            flowAssign.setHandleUser(s);
            flowAssign.setHandleHour(split1[0]);
            flowAssign.setParentAssignId(assignId);
            flowAssign.setHandleStatus(1);
            flowAssignService.insertAssign(flowAssign);
        }

        StringBuffer stringBuffer1 = new StringBuffer();

        if (flowAssignWithBLOBs != null && !flowAssignWithBLOBs.isEmpty()) {
            String[] split3 = jingbanUser.split(",");
            int i = 0;
            int o = 0;
            for (String s : split3) {
                for (FlowAssignWithBLOBs flowAssignWithBLOBs1 : flowAssignWithBLOBs) {
                    String handleUser = flowAssignWithBLOBs1.getHandleUser();
                    if (!s.equals(flowAssignWithBLOBs1.getHandleUser())) {
                        i++;
                    }

                }
                if (i == flowAssignWithBLOBs.size()) {
                    if (o == 0) {
                        stringBuffer1.append(s);
                    }
                    if (o > 0) {
                        stringBuffer1.append("," + s);
                    }
                    o++;
                    i = 0;
                }
            }

            jingbanUser = stringBuffer1.toString();
        }

        /*flowPrcs="2";*/

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        beginTime = sdf.format(date);
        String[] split2 = jingbanUser.split(",");
        StringBuffer stringBuffer = new StringBuffer();
        int x = 0;
        for (String s1 : split2) {
            if (!s1.equals(user.getUserId())) {
                if (x == 0) {
                    stringBuffer.append(s1);

                }
                if (x > 0) {
                    stringBuffer.append("," + s1);
                }
                x++;
            }
        }
        jingbanUser = stringBuffer.toString();
        if (StringUtils.checkNull(jingbanUser)) {
            ToJson<FlowRunPrcs> toJson = new ToJson<FlowRunPrcs>();
            toJson.setFlag(0);
            toJson.setMsg("OK");
            return toJson;
        }
        return wfeRunner.getWfeFlowRunInfo().savework2(runId, runName, prcsId, flowPrcs, beginTime, beginUser, jingbanUser, viewUser, user, currentPrcsId, topDefault, tabId, tableName, smsContent, smsType, orgadd,parent,topFlag);

        //return wfeRunner.getWfeFlowRunInfo().savework(runId, runName, flowId, prcsId, prcsFlag, flowStep, flowPrcs, beginTime, beginUser, jingbanUser, viewUser, user, currentPrcsId, topDefault, tabId, branchCount);

    }

    @RequestMapping("/query")
    @ResponseBody
    public ToJson<FlowAssign> query(FlowAssign flowAssign, HttpServletRequest request) {
        return flowAssignService.query(flowAssign, request);
    }

    @RequestMapping("/checkAssign")
    @ResponseBody
    public ToJson<FlowAssignWithBLOBs> checkAssign(HttpServletRequest request, Integer runId,Integer prcsId,Integer flowPrcs) {
        return flowAssignService.checkAssign(request,runId,prcsId,flowPrcs);
    }
}

